<template>
    <div class="userDefined1"> 
        <el-row class="titleName">
            <el-col :span="12" class="title">
                <span v-if="pageData.pageType !== 'blank'"><label>场景功能：</label>PPT幻灯片</span>
                <span v-else-if="pageData.pageType === 'blank'"><label>场景功能：</label>自定义空白页</span>
            </el-col>
            <el-col :span="12" style="text-align:right;">
                <label>场景页名称：</label>
                <el-input
                    style="width: 260px"
                    placeholder="自定义页"
                    v-model="pageData.pageName"
                    clearable>
                </el-input>
                <el-button type="primary" @click.stop="alterSceneName()">修改</el-button>
            </el-col>
        </el-row>           
        <div class="main_block">
            <el-form label-width="120px">
                <backgComponent @change="bgChange" :bgdata="pageData.d3Config">
                    <el-button slot="right" style="margin-left:10px" type="danger" @click="goTpshow">高级编辑</el-button>
                </backgComponent>         
            </el-form>
        </div>
        <el-dialog
            top="40px"
            :visible="sfxLibraryVisibly"
            width="660px"
            title="特效库"
            @close="sfxLibraryVisibly = false"
            append-to-body
            custom-class="definedModal">
            <specialLibrary @selected="selectCurrentSpx" @close="sfxLibraryVisibly = false"></specialLibrary>
        </el-dialog>
        <footerButtons @save="saveData"></footerButtons>          
    </div>
</template>

<script>
    import imagesLibrary from '../baseSetting/library/imagesLibrary';
    import specialLibrary from '../baseSetting/library/specialLibrary';
    import { generateNumberID } from '@/utils/util';
    import backgComponent from "@/pages/common/bgComponent"  
    import bgImage from '../../../../../src/assets/imgs/fj.jpg';
    import { configMerge } from '@/utils/pageConfig'; 
    import { deepCopy } from '@/utils/util';
    export default {
        name: 'userDefined',
        components: {
            imagesLibrary,
            specialLibrary,
            backgComponent
        },         
        data() {
            return {  
                secondPlaceModal: false,
                picLibraryVisibly: false,
                sfxLibraryVisibly: false,
                hashShape:[],
                pageData:{
                    bgImage:bgImage,
                    screenEffect:{
                        name:'特效名称'
                    },
                    pageName:"", 
                    pageType:"blank"
                },
                screenElements:[],                                
            }
        },
        created() {
            if(this.$route.path.indexOf('add') !== -1){ //判断是否为修改
                this.pageidBigint = null;
                this.pageData.pageType = "blank";
            }else{ 
                this.pageidBigint = this.$route.name 
                this.seachPageData();                   
            }                
        },         
        methods:{
            bgChange(data, url){
                this.pageData.bgImage = url;
                this.pageData.d3Config = data;
            }, 
            // 特效库选择结果
            selectCurrentSpx(data) {                
            },
            seachPageData(){
                this.$api.post('/stScenepage/scenePageView', {pageidBigint: this.pageidBigint}, data => {
                    this.pageData.pageName = data.name;  
                    this.pageData.num = data.num;                    
                    if(data.elements.length>0){
                        let elementsList = [];
                        // console.info(data);                        
                        elementsList = deepCopy(data.elements);
                        elementsList.forEach((elem, i) => {  
                            this.pageData.pageType = "PPT";                          
                            if(elem.hashShape && elem.shapes.length>0){                                
                                this.hashShape = elem.shapes;                         
                            }
                            if(elem.type ==="sppt" || elem.accessSlideUrl){   
                                this.pageData = configMerge(elem);  
                                this.pageData.pageName = data.name;                                                           
                                elementsList[i] = this.pageData; 
                                elementsList[i].id = this.generateNumbID();
                                elementsList[i].type = this.pageData.type = "sppt";
                                this.pageData.pageType = "PPT";
                            }
                            if(elem.type ==="3"){
                                this.pageData.d3Config = elem.properties.d3Config;
                                this.pageData.bgImage = elem.properties.bgImage;
                                this.pageData.pageType = elem.properties.pageType;
                            }                            
                        })
                        this.screenElements = deepCopy(elementsList);
                    }else{
                        this.screenElements = [];
                    }                                                                                                                                                                                    
                }, fal => {
                    this.$message.error(fal);
                });                 
            },
            alterSceneName(){ //修改场景名
                if(!this.pageData.pageName){
                    this.$message.warning('场景名不能为空喔！');
                    return false;
                }else{
                    this.saveData();
                }                
            },
            saveData(goTpshow){
                if(this.$route.path.indexOf('add') !== -1){ //判断是否为修改
                    this.pageidBigint = null;
                }else{ 
                    this.pageidBigint = this.$route.name                    
                } 
                if (!this.pageData.pageName) {
                    return this.$message({
                        message: '场景页名称不能为空',
                        type: 'warning',
                    });
                }
                if(this.hashShape && this.hashShape.length>0){
                    this.hashShape.forEach((shape,ind) => {
                        shape = configMerge(shape);
                        shape.type = "h";
                        shape.pageType = "PPT"; 
                        shape.sceneId= this.$route.query.sceneId;
                        shape.pageId= this.pageidBigint;
                        shape.id = this.generateNumbID(); 
                        shape.css.width = shape.width;
                        shape.css.height = shape.height; 
                        shape.css.top = shape.x;
                        shape.css.left = shape.y; 
                        shape.css.zIndex = ind;
                        shape.css.imageCr = shape.accessShapUrl;
                        shape.properties.items = null;
                        shape.properties.src = shape.accessShapUrl;                                                 
                        this.screenElements.push(shape);                        
                    })
                    this.hashShape = []; 
                    if(!this.screenElements[0].type){this.screenElements.splice(0, 1)}                   
                }
                // if(this.screenElements.length===0 && this.pageData.pageType !== "blank"){
                //     this.pageData.type = "sppt";
                //     // this.pageData.typeFlag = "ppt"                 
                //     this.screenElements.push(configMerge(_.extend(true, {}, this.pageData)));                
                // }
                let param =  {
                    sceneid: this.$route.query.sceneId, //场景号
                    name: this.pageData.pageName, //场景页名
                    num: this.pageData.num||1,
                    pageidBigint: this.pageidBigint,  //场景页主键修改时传
                    elements: this.screenElements,  //（存储基础信息List
                    pageType: 6    //页类型，参数自己定义区分出四个基本页）
                },bgIndex;                 
                bgIndex = param.elements.findIndex(b => b.type === '3')
                console.info(bgIndex);
                if(bgIndex !== -1){
                    param.elements[bgIndex].properties.imgSrc = this.pageData.bgImage;
                    param.elements[bgIndex].properties.d3Config = this.pageData.d3Config
                    param.elements[bgIndex].properties.pageType = this.pageData.pageType;
                }else{
                    // 判断是否选择了背景图,选择了背景图则在elements中添加背景组件
                    if (this.pageData.d3Config) {
                        var bgConfig = {
                            sceneId: this.$route.query.sceneId,
                            pageId: this.pageidBigint,
                            id: generateNumberID(),
                            type: '3',
                        };
                        // console.info(configMerge(bgConfig));
                        let bgC = deepCopy(configMerge(bgConfig))
                            bgC.properties.imgSrc = this.pageData.imgSrc;
                            bgC.properties.d3Config = this.pageData.d3Config;
                            bgC.properties.pageType = this.pageData.pageType;                            
                            param.elements.push(bgC);
                    }
                }

                this.$api.post(
                '/stScenepage/savePage',
                param,
                response => {
                    let pageId = response;
                    this.$bus.$emit('menuRefresh', this.$route.path, pageId);
                    this.$message({
                        message: '保存成功',
                        type: 'success',
                    });
                    // 点击高级编辑，先保存当前设置，然后跳转到编辑器
                    if(goTpshow){
                        var {origin} = window.location;
                        if(origin.indexOf("localhost") > -1){
                            origin = "https://office2.cn"
                        }
                        this.$nextTick(() => {
                            let token = sessionStorage.getItem('token');
                            var url = `${ origin }/staticft/#/scene/create/${
                                this.$route.query.sceneId
                            }?pageId=${this.pageData.num || 1}&type=smartscreen&token=${token}`;
                            window.location.replace(url);
                        }); 
                    }else{
                        this.seachPageData();
                    }
                },
                fal => {
                    this.$message.error(fal);
                });
            },
            goTpshow(){  //高级编辑
                this.saveData(true);               
            },
            generateNumbID(){
                return parseInt(''+ +new Date().getHours() + new Date().getYear() + new Date().getMinutes() + parseInt(Math.random() * 100))
            },
        }      
    };
</script>

<style scoped lang="scss">
    .userDefined1{
        padding-top:20px;
        padding-bottom: 30px;
        .titleName {
            margin: 0px 20px 20px;
            .title{
                line-height: 30px;
                font-size: 24px;
            }
            label{
                font-size: 14px;
                margin-right: 10px;
            }
        }        
        .main_block{
            width: calc(100% - 40px);
            height: calc(100% - 60px);
            padding:30px 20px 30px 20px;
            border-radius: 10px;
            position: relative;
            background-color: #fff;
            margin: 10px auto; 
        }
        .reminder{
            font-size: 12px;
            color: #afafaf;
        }
        .uploading{
            padding:8px 40px;
        }
        .el-icon-upload{
            font-size: 28px;
            margin-left: -10px;
            width: 35px;
            float: left;
        }
        .text{
            font-style: normal;
            font-size: 16px;
            font-weight: 600;
        }
        .mind{
            margin-top: 20px;
            margin-bottom: 30px;
            font-size: 18px;
            font-family: Arial, Helvetica, sans-serif;
        }
        .box-card{
            text-align: center;
            padding-bottom: 20px;
            padding-top: 10px;
            margin-bottom: 30px;
        }
    }
    .vertical-top {
        button {
            vertical-align: top;
        }
        .img-container {
            width: 160px;
            min-height: 80px;
            border: 1px solid #eee;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            margin-right:15px;
            .bg-img {
                max-width: 160px;
            }
            span {
                color: #afafaf;
            }
        }
        .effect-name{
            color: #373737;
            margin-right:15px;
        }            
    }  
</style>